package cn.car.service.impl;

import cn.car.domains.bo.QueryPermissionBo;
import cn.car.domains.entity.SysPermissionEntity;
import cn.car.exception.CarAccessControlException;
import cn.car.mapper.SysPermissionMapper;
import cn.car.service.SysPermissionService;
import jakarta.annotation.Resource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysPermissionServiceImpl implements SysPermissionService {

    @Resource
    private SysPermissionMapper sysPermissionMapper;

    @Override
    public Long addPermission(SysPermissionEntity permission) {
        // 执行插入操作
        int rows;
        try {
            rows = sysPermissionMapper.insertPermission(permission);
        } catch (DuplicateKeyException e) {
            throw CarAccessControlException.DATE_EXIST;
        }

        if (rows != 1) {
            throw CarAccessControlException.INSERT_ERROR.newInstance("插入权限失败");
        }
        return permission.getId();
    }

    @Override
    public SysPermissionEntity getPermissionById(Long id) {
        return sysPermissionMapper.selectById(id);
    }

    @Override
    public SysPermissionEntity getPermissionByCode(String permissionCode) {
        return sysPermissionMapper.selectByCode(permissionCode);
    }

    @Override
    public void updatePermission(SysPermissionEntity permission) {
        // 校验ID是否存在
        if (permission.getId() == null) {
            throw CarAccessControlException.PARAMS_ERROR.newInstance("更新id不能为空");
        }

        // 执行更新操作
        int rows = sysPermissionMapper.updatePermission(permission);

        if (rows != 1) {
            throw CarAccessControlException.UPDATE_NOT_EXIST;
        }
    }

    @Override
    public void deletePermission(Long id) {
        // 校验ID是否存在
        if (id == null) {
            throw CarAccessControlException.PARAMS_ERROR.newInstance("删除id不能为空");
        }

        // 执行删除操作
        int rows = sysPermissionMapper.deleteById(id);

        if (rows != 1) {
            throw CarAccessControlException.DELETE_NOT_EXIST;
        }
    }

    @Override
    public List<SysPermissionEntity> list(QueryPermissionBo query) {
        return sysPermissionMapper.selectList(query);
    }
}
